﻿using UnityEditor;
using UnityEngine;
using System.Collections;

/// <summary>
/// 压缩AssetBundle包打包成zip压缩包
/// </summary>
public class CompresionAssetBundle 
{
    [MenuItem("AssetBundle/CompresionAssetBundleToZip_Android   压缩", false, 401)]
    public static void CompresionAssetBundleToZip_Android()
    {
        CompresionAssetBundleToZip(Platform.GetPlatformFolder(RuntimePlatform.Android));
    }

    [MenuItem("AssetBundle/CompresionAssetBundleToZip_IOS   压缩", false, 402)]
    public static void CompresionAssetBundleToZip_IOS()
    {
        CompresionAssetBundleToZip(Platform.GetPlatformFolder(RuntimePlatform.IPhonePlayer));
    }

    [MenuItem("AssetBundle/CompresionAssetBundleToZip_Windows   压缩", false, 403)]
    public static void CompresionAssetBundleToZip_Windows()
    {
        CompresionAssetBundleToZip(Platform.GetPlatformFolder(RuntimePlatform.WindowsEditor));
    }

    public static void CompresionAssetBundleToZip(string target_folder)
    {
        var sources_files_temp_dir_path = FileTool.PathCombine(AssetBundleConfig.TempAssetBundleDirPath, target_folder);
        var full_zip_file_path = FileTool.PathCombine(AssetBundleConfig.TempAssetBundleDirPath_ZIP, target_folder + CompresionTool.extension_name);
        //full_zip_file_path = FileTool.PathCombine(full_zip_file_path,target_folder )
        CompresionAssetbundle(sources_files_temp_dir_path, full_zip_file_path);
        System.Diagnostics.Process.Start("Explorer", @"file:///" + full_zip_file_path);
    }

    /// <summary>
    /// 对文件进行压缩
    /// </summary>
    /// <param name="sources_files_temp_dir_path">对比出不同的文件后的目录名称</param>
    /// <param name="m_zip_file_name">存放压缩包绝对路径</param>
    private static void CompresionAssetbundle(string sources_files_temp_dir_path, string m_zip_file_name)
    {
        if (!System.IO.Directory.Exists(sources_files_temp_dir_path))
        {
            return;
        }

        var dir_name = System.IO.Path.GetDirectoryName(m_zip_file_name);
        if (System.IO.Directory.Exists(dir_name))
        {
            FileTool.ForeachFiles(dir_name, FileTool.ForeachEnum.FileAndDir, (string full_file_name) =>
            {
                UnityEditor.FileUtil.DeleteFileOrDirectory(full_file_name);
            });
        }
        else
        {
            System.IO.Directory.CreateDirectory(dir_name);
        }

        CompresionTool.Compress(AssetBundleConfig.TempAssetBundleDirPath, m_zip_file_name, null, null, (string full_file_name) =>
        {
            // 如果是压缩文件就不能再去压缩了
            if (full_file_name.EndsWith(CompresionTool.extension_name))
            {
                return false;
            }

            // 例外文件不压缩
            Debug.Log("___CheckCanCompressFile  " + full_file_name);
            if (full_file_name.EndsWith("hash_code.txt"))
            {
                return false;
            }
            return true;
        });
    }
}
